<template>
    <div>
        <el-input v-model="searchName" placeholder="搜索内容" ></el-input>
        <el-button type="primary" @click="search">点击搜索</el-button>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="日期" width="180"></el-table-column>
            <el-table-column prop="name" label="姓名" width="180"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="" label="操作">
                <!-- 插槽获取本行的id -->
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" 
                    @click="changeBranch = true;editUser(scope.$index,scope.row)">修改</el-button>

                    <el-button class="btnDel" type="primary" 
                    @click="handleDelete(scope.$index,scope.row)">删除</el-button>  
                </template>
            </el-table-column>
        </el-table>

        <el-button class="btnAdd" type="primary" @click="dialogVisible = true">点击新增</el-button>
        
        <!-- 新增的弹窗 -->
        <el-dialog title="新增弹窗" :visible.sync ='dialogVisible' width="35%">
            <el-form  label-width="90px" > 
                <el-form-item label="姓名">
                    <el-input v-model="input.name"></el-input>
                </el-form-item>
                <el-form-item label="日期">
                    <el-input v-model="input.date"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="input.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false;branchAdd()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改的弹窗 -->
        <el-dialog 
        title="修改信息" 
        :visible.sync ='changeBranch'
        width="35%">
            <el-form  label-width="90px" > 
                <el-form-item label="姓名">
                    <el-input class="inputName" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="日期">
                    <el-input class="inputDate" v-model="form.date"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input class="inputAddress" v-model="form.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="changeBranch = false">取 消</el-button>
                <el-button type="primary" @click="changeBranch = false;handlePut()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 
            实现思路：首先有两个数组 showedData 和 tableData。
            showedData用来放当前页的数据，tableData用来放所有数据。
            为表格绑定@sort-change事件，
            当点击表头的排序icon时，调用sort_change方法,
            该方法内部调用的sortFun方法可以为tableData进行排序，showedData显示排好序的前四条数据。
         -->
        <input type="text" v-model="searchVal">

        <el-table
            :data="list"
            style="width: 100%;"
           >
           <!-- @sort-change="sort_change" -->

            <template v-for="(item,index) in cities">
                <el-table-column v-if="item.type=='sort'" :prop="item.prop" :label="item.label" :key="index" sortable="custom"></el-table-column>
                <el-table-column v-else :prop="item.prop" :label="item.label" :key="item.prop" ></el-table-column>
            </template>

        </el-table>

        <el-button @click="orderFn('followNum',true)" >排 序 ↑</el-button>
        <!-- <el-button @click="orderFn('followNum',true)" >排 序 ↓</el-button> -->
        <div>
            <template>
                <el-button 
                v-for="(item,index) in cities"
                :key="index" 
                :label="item.prop"
                @click="orderFn(`${item.prop}`,true)" >{{ `${item.label}` }}</el-button>
            </template>
        </div>

        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageSize" 
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>

    </div>
</template>

<script>
import api from '../../api';
import axios from 'axios';
export default {
    name: 'TableView',
    data(){
        return{
            searchName:'',
            dialogVisible:false,
            changeBranch:false,
            input:{ id:'', name:'', address:'', date:'' },
            form:{ id:'', name:'', address:'', date:'' },
            tableData: [],
            // 排序数据
            // 表头数组，数组中根据type判断该列是否可以排序
            cities:[
                {
                    prop:'position',
                    label:'城市',
                },
                {
                    prop:'followNum',
                    label:'新增人数',
                    type:'sort',
                },
                {
                    prop:'unFollowNum',
                    label:'取消关注人数',
                    type:'sort',
                },
                {
                    prop:'increaseNum',
                    label:'净增人数',
                    type:'sort',
                },
                {
                    prop:'currdateFollowNum',
                    label:'累积人数',
                    type:'sort',
                }
            ], 
             // 当前页数
            pageNum: 1,

            // 每页条数
            pageSize: 4, 

            // 总数
            total: 5, 

            // 当前页的数据
            showedData:[
                {
                    position:'成都',
                    followNum:'11',
                    unFollowNum:'22',
                    increaseNum:'33',
                    currdateFollowNum:44
                },
                {
                    position:'长沙',
                    followNum:'111',
                    unFollowNum:'222',
                    increaseNum:'333',
                    currdateFollowNum:444
                },
                {
                    position:'上海',
                    followNum:'1',
                    unFollowNum:'2',
                    increaseNum:'3',
                    currdateFollowNum:4
                },
                {
                    position:'北京',
                    followNum:'11111',
                    unFollowNum:'22222',
                    increaseNum:'33333',
                    currdateFollowNum:44444
                }
            ], 

            // 所有的数据 
            cityTableData: [
                {
                    position:'上海',
                    followNum:'1',
                    unFollowNum:'2',
                    increaseNum:'3',
                    currdateFollowNum:4
                },
                {
                    position:'成都',
                    followNum:'11',
                    unFollowNum:'22',
                    increaseNum:'33',
                    currdateFollowNum:44
                },
                {
                    position:'长沙',
                    followNum:'111',
                    unFollowNum:'222',
                    increaseNum:'333',
                    currdateFollowNum:444
                },
                {
                    position:'西安',
                    followNum:'1111',
                    unFollowNum:'2222',
                    increaseNum:'3333',
                    currdateFollowNum:4444
                },
                {
                    position:'北京',
                    followNum:'11111',
                    unFollowNum:'22222',
                    increaseNum:'33333',
                    currdateFollowNum:44444
                }
            ], 

            // 排序
            searchVal:'',    //默认输入为空
            letter:'',       //默认不排序 // 排序字段
            original:false,   //默认从小到大排列

        }
    },
    methods:{
        // 实验函数
        init(res){
            console.log('Table实验函数：',res);
        },
        // 请求数据
        getTableData(){
            api.xuData.getAddDeletePostGet().then(res=>{
                if(!this.searchName){
                    this.tableData = res.data
                }else{
                    this.tableData = res.data.filter(item => item.name == this.searchName)
                }
            })
        },
         // 增加
        branchAdd(){
            var data = { name:this.input.name, 
                address:this.input.address,
                date:this.input.date}
            this.handleAdd(data)
        },
        handleAdd(data){
            axios.post('http://localhost:3001/addDeletePostGet/',data)
            // 'http://localhost:3001/addDeletePostGet/'
            // `http://localhost:3001/${addDeletePostGet}/`
            .then((res) => {
                console.log(res);
                window.location.reload();
            }).catch((err) => {console.log(err);});
        },
        // 删除
        handleDelete(index, row) {
            axios.delete(`http://localhost:3001/addDeletePostGet/${row.id}`)
            .then((res) => {
                console.log(res);
                // 自动刷新页面
                window.location.reload();
            }).catch((err) => {console.log(err);});
        },
        // 修改
        editUser(index, row){
            this.form = {
                id:row.id,
                name:row.name,
                address:row.address,
                date:row.date}
        },
        handlePut(){
            axios.put(`http://localhost:3001/addDeletePostGet/${this.form.id}`,{
                id:this.form.id,
                name:this.form.name,
                address:this.form.address,
                date:this.form.date
            }).then((res) => {
                console.log(res);
            }).catch((err) => { console.log(err);});
            window.location.reload();
        },
        // 搜索
        search(){
            this.getTableData()
            console.log('你点击了搜索');
        },
        // 排序1
        sort_change(column) { // column是个形参，具体查看element-ui文档
            this.pageNum = 1 // return to the first page after sorting
            this.total = this.cityTableData.length
            this.cityTableData = this.cityTableData.sort(this.sortFun(column.prop, column.order === 'ascending'));
            this.showedData = this.cityTableData.slice(0, this.pageSize) // 排序完显示到第一页
        },
        sortFun (attr, rev) {
            //第一个参数传入info里的prop表示排的是哪一列，第二个参数是升还是降排序
            if (rev == undefined) {
                rev = 1;
            } else {
                rev = (rev) ? 1 : -1;
            }
            return function (a, b) {
                a = a[attr];
                b = b[attr];
                if (a < b) {
                    return rev * -1;
                }
                if (a > b) {
                    return rev * 1;
                }
                return 0;
            }
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.showedData = this.tableData.slice((this.pageNum-1)*this.pageSize,this.pageNum*this.pageSize)
        },
        // 排序2
        orderFn ( letter,original  ){
            // , original
            this.letter = letter; //排序字段
            this.original = original; //排序方式
            console.log(' this.letter:', this.letter);
            console.log(' this.original:', this.original);
        }
    },
    // 计算属性
    computed:{
        // 通过计算属性过滤数据
        list:function(){
            var _this = this;
            // 筛选
            var arrGoods = [];
            for (var i = 0; i < this.cityTableData.length; i++){
                // 如果匹配成功，向空数组添加数据
                if(this.cityTableData[i].position.search(this.searchVal) != -1){
                    arrGoods.push(this.cityTableData[i]);
                }
            }
            // 升序降序排列
            // false:升序 true：降序
            if ( this.letter != ''){
                arrGoods.sort(function(a,b){
                    if(_this.original){
                        return b[_this.letter] - a[_this.letter];
                    } else {
                        return a[_this.letter] - b[_this.letter];
                    }
                });
            }
            // _this.total = 0;
            // for (var i = 0;i < arrGoods.length;i++){
            //     _this.total += arrGoods[i].price;
            // }
            return arrGoods;

        },
        // 默认总价
        // total:function(){
        //     return this.total;
        // }
    },
    created(){
        this.getTableData()
    }
};
</script>

<style scoped ></style>